<template>
  <div>
    <el-form ref="queryForm"
      class="query-form"
      :model="queryParams"
      size="small"
      :inline="true">
      <el-form-item label="权益类型"
        prop="unit_id">
        <el-select v-model="queryParams.unit_id">
          <el-option v-for="item in chargeUnitList" :value="item.unit_id" :label="item.internal_name" :key="item.unit_id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="搜索类型"
        prop="search_type">
        <el-select v-model="queryParams.search_type" clearable>
          <el-option
            label="订单检索"
            value="order_no"/>
          <el-option
            label="用户id检索"
            value="user_id" />
          <el-option
            label="用户手机号检索"
            value="mobile" />
          <el-option
            label="用户昵称检索"
            value="nick_name" />
        </el-select>
      </el-form-item>
      <el-form-item label="搜索值" prop="search">
        <el-input v-model="queryParams.search"
          placeholder="输入加购包ID、名称"
          clearable/>
      </el-form-item>
      <el-form-item label="当前数值范围" style="max-width: 300px;">
        <div class="input-range">
          <el-form-item prop="start_count" style="margin:0;padding:0">
            <el-input-number v-model="queryParams.start_count"
            :precision="0"  :min="0" clearable size="small" style="width: 83px" />
          </el-form-item>
          -
          <el-form-item prop="stop_count" style="margin:0;padding:0">
            <el-input-number v-model="queryParams.stop_count"
            :precision="0"  :min="0" clearable size="small" style="width: 83px"/>
          </el-form-item>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
          size="small"
          @click="handleQuery">搜索</el-button>
        <el-button size="small"
          @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading"
      :data="dataList">
      <el-table-column label="序号" type="index"  width="100" > </el-table-column>
      <el-table-column label="用户id"
        min-width="120"
        prop="user_id" />
      <el-table-column label="用户昵称"
        min-width="120"
        prop="nick_name">
      </el-table-column>
      <el-table-column label="用户手机号"
        min-width="120"
        prop="mobile">
      </el-table-column>
      <el-table-column label="当前数值"
        width="120"
        prop="count" />
      <el-table-column label="数值更新时间"
        min-width="120">
        <template slot-scope="scope">
          <div>{{ scope.row.updated_at | parseTime }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作"
        width="120"
        fixed="right">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            @click="handleDetail(scope.row)">数值明细</el-button>
          <el-button
            size="small"
            type="text"
            @click="handleHeXiao(scope.row)">核销</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getList" />
    <el-dialog title="数值明细"
      :visible.sync="open"
      width="800px"
      :close-on-click-modal="false"
      @closed="onDialogClosed">
      <div class="detail-content" v-if="detailItem">
        <div>用户ID:{{ detailItem.user_id }}</div>
        <div>用户名:{{ detailItem.nick_name }}</div>
        <div>用户手机号:{{ detailItem.mobile }}</div>
        <div>权益类型/当前数值:{{ getCurrentEquityName }}/{{ detailItem.count }}</div>
        <el-button type="primary" size="small" @click="handleHeXiao(detailItem)">核销</el-button>
      </div>
      <el-form ref="queryForm1"
        class="query-form"
        :model="queryParams1"
        size="small"
        :inline="true">
        <el-form-item label="类型" prop="op_type">
          <el-select v-model="queryParams1.op_type">
            <el-option
              label="全部"
              value=""/>
            <el-option
              label="收入"
              value="add" />
            <el-option
              label="支出"
              value="dec" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间" prop="dateRange">
          <el-date-picker v-model="queryParams1.dateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
            size="small"
            @click="handleQuery1">搜索</el-button>
          <el-button size="small"
            @click="resetQuery1">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading1"
        :data="dataList1">
        <el-table-column label="类型"
          width="80">
          <template #default="{row}">
            <p class="text"
            >{{row.op_type==='dec'?'支出':'收入'}}</p>
          </template>
        </el-table-column>
        <el-table-column label="流水号">
          <template #default="{row}">
            <div>[{{row.title}}]</div>
            <div>{{ row.third_id }}</div>
          </template>
        </el-table-column>
        <el-table-column label="数量"
          width="100">
          <template #default="{row}">
            <p class="text"
            >{{row.op_type==='dec'?'-':'+'}}{{ row.amount }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作时间"
          width="180" >
          <template slot-scope="scope">
            <div>{{ scope.row.created_at | parseTime }}</div>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total1 > 0"
        :total="total1"
        :page.sync="queryParams1.page"
        :limit.sync="queryParams1.page_size"
        @pagination="getList1" />
    </el-dialog>
    <el-dialog title="核销"
      :visible.sync="open1"
      width="400px"
      @closed="onDialogClosed1"
      :close-on-click-modal="false">
      <div class="detail-content" v-if="detailItem">
        <div>权益类型/当前数值:{{ getCurrentEquityName }}/{{ detailItem.count }}</div>
      </div>
      <el-form ref="queryForm2"
        :rules="rules2"
        :model="queryParams2">
        <el-form-item label="事项"  prop="title">
          <el-input maxlength="50" v-model="queryParams2.title" placeholder="请输入事项" clearable style="width:200px"/>
        </el-form-item>

        <el-form-item label="核销类型" prop="op_type">
          <el-radio-group v-model="queryParams2.op_type" size="small">
            <el-radio-button label="dec">减少</el-radio-button>
            <el-radio-button label="add">增加</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="核销数值" prop="amount">
          <el-input-number v-model="queryParams2.amount"
            placeholder=""
            size="small"
            :min="0"
            :precision="0"/>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary"
          :loading="saveLoading"
          @click="submitForm">确 认</el-button>
        <el-button @click="open1 = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getPackageDetailList, getPackageDetailInfoList, heXiao } from '@/api/addition'
import { getChargeUnit } from '@/api/system'
import { parseTime } from '@/utils/'
export default {
  name: 'additionDetail',
  data () {
    return {
      loading: false,
      saveLoading: false,
      chargeUnitList: [],
      queryParams: {
        unit_id: '',
        start_count: undefined,
        stop_count: undefined,
        search_type: '',
        search: '',
        page: 1,
        page_size: 10
      },
      dataList: [],
      total: 0,
      open: false,
      open1: false,
      detailItem: null,
      loading1: false,
      queryParams1: {
        user_id: '',
        unit_id: '',
        bus_key: '',
        op_type: '',
        dateRange: null,
        page: 1,
        page_size: 5
      },
      dataList1: [],
      total1: 0,
      queryParams2: {
        user_id: '',
        unit_id: '',
        op_type: 'dec',
        title: '服务扣除', // 默认是这个
        amount: 1,
        source: 'admin', // 写死admin
        bus_key: '',
        cycle: ''
      },
      rules2: {
        title: [{ required: true, message: '事项不能为空', trigger: 'blur' }]
      }
    }
  },
  filters: {
    parseTime
  },
  computed: {
    getCurrentEquityName () {
      if (this.chargeUnitList && this.chargeUnitList.length && this.queryParams.unit_id) {
        return this.chargeUnitList.find(item => item.unit_id === this.queryParams.unit_id).name
      }
      return ''
    }
  },
  created () {
    getChargeUnit().then(res => {
      this.chargeUnitList = res.data.list
      this.queryParams.unit_id = this.chargeUnitList[0].unit_id
      this.getList()
    })
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.page = 1
      this.getList()
    },
    handleQuery1 () {
      this.queryParams1.page = 1
      this.getList1()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm('queryForm')
    },
    resetQuery1 () {
      this.resetForm('queryForm1')
    },
    handleAdd () {
      this.open = true
    },
    getList () {
      if (!this.queryParams.unit_id) {
        this.msgError('请先选择权益类型')
        return
      }
      if (this.queryParams.search_type && !this.queryParams.search) {
        this.msgError('请输入搜索值')
        return
      }
      if (!this.queryParams.search_type && this.queryParams.search) {
        this.msgError('请选择搜索类型')
        return
      }
      if (this.queryParams.start_count && this.queryParams.stop_count && Number(this.queryParams.stop_count) < Number(this.queryParams.start_count)) {
        this.msgError('最低值不能大于最高值')
        return
      }
      this.loading = true
      getPackageDetailList(this.queryParams).then(res => {
        const data = res.data || {}
        this.dataList = (data.list || [])
        this.dataList.map(item => {
          item.unit_id = this.queryParams.unit_id
        })
        this.total = data.count
        if (this.detailItem && this.open) {
          this.detailItem = this.dataList.find(item => item.user_id === this.detailItem.user_id)
        }
      }).catch(() => {
        this.dataList = []
        this.total = 0
      }).finally(() => {
        this.loading = false
      })
    },
    getList1 () {
      this.loading1 = true

      const queryParams = { ...this.queryParams1 }

      if (queryParams.dateRange) {
        queryParams.begin_at = queryParams.dateRange[0]
        queryParams.end_at = queryParams.dateRange[1]
      } else {
        queryParams.begin_at = null
        queryParams.end_at = null
      }

      delete queryParams.dateRange

      getPackageDetailInfoList(queryParams).then(res => {
        const data = res.data || {}
        this.dataList1 = (data.list || [])
        this.total1 = data.count
      }).catch(() => {
        this.dataList1 = []
        this.total1 = 0
      }).finally(() => {
        this.loading1 = false
      })
    },
    getItemsSetting (row) {
      const str = (row.items || []).map(item => {
        return item.count + item.item_name
      })
      return str.join(';')
    },
    /** 删除按钮操作 */
    handleHeXiao (row) {
      this.open1 = true
      this.detailItem = row
      this.queryParams2.user_id = row.user_id
      this.queryParams2.unit_id = row.unit_id
      this.queryParams2.bus_key = row.bus_key
      this.queryParams2.cycle = row.cycle
    },
    handleDetail (row) {
      this.open = true
      this.detailItem = row
      this.queryParams1.user_id = row.user_id
      this.queryParams1.unit_id = row.unit_id
      this.queryParams1.bus_key = row.bus_key
      this.getList1()
    },
    submitForm () {
      this.$refs['queryForm2'].validate(valid => {
        if (valid) {
          if (this.queryParams2.amount === 0) {
            this.msgError('核销数值不能为0')
            return
          }

          if (this.queryParams2.op_type === 'dec' && (this.queryParams2.amount > this.detailItem.count)) {
            this.msgError('核销数值不能大于当前数值')
            return
          }

          this.saveLoading = true
          heXiao(this.queryParams2).then(() => {
            this.msgSuccess(`操作成功`)
            this.open1 = false
            this.handleQuery()
            if (this.open) {
              this.handleQuery1()
            }
          }).finally(() => {
            this.saveLoading = false
          })
        }
      })
    },
    onDialogClosed1 () {
      this.resetForm('queryForm2')
      if (!this.open) { // 第一个弹框打开的时候，不能清除
        this.detailItem = null
      }
    },
    onDialogClosed () {
      this.resetForm('queryForm1')
      this.detailItem = null
      this.loading1 = false
      this.total1 = 0
      this.dataList1 = []
    }
  }
}
</script>
<style lang="scss" scoped>
 .input-range{
  display: flex;
  align-items: center;
  gap:10px;
 }
 .detail-content{
  display: flex;
  column-gap:50px;
  row-gap:20px;
  flex-wrap: wrap;
  margin-bottom: 20px;
  align-items: center;
 }
</style>
